/**
 * 
 */
package com.feeyin.radar.crm.dao.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.feeyin.radar.commons.DateUtils;
import com.feeyin.radar.commons.Entry;
import com.feeyin.radar.commons.Page;
import com.feeyin.radar.crm.dao.ContractCaseDAO;
import com.feeyin.radar.crm.model.CaseAttach;
import com.feeyin.radar.crm.model.ContractCase;
import com.feeyin.radar.crm.model.CostManage;
import com.feeyin.radar.crm.model.Process;
import com.feeyin.radar.crm.model.ProcessGroup;
import com.feeyin.radar.crm.model.SubContractCase;

/**
 * @author E547415
 *
 */
public class ContractCaseDAOImpl extends SqlMapClientDaoSupport implements ContractCaseDAO
{
	public List<ContractCase> getContractCasesByContractCode(String contractCode) {
		if(contractCode == null)
			return null;
		ContractCase contractCase = new ContractCase();
		contractCase.setContractId(contractCode);
		return getSqlMapClientTemplate().queryForList("getContractCaseByDynamic", contractCase);
	}	
	
	public ContractCase getContractCasesById(Integer caseId) {
		if(caseId == null)
			return null;
		ContractCase contractCase = new ContractCase();
		contractCase.setId(caseId);
		return (ContractCase)getSqlMapClientTemplate().queryForObject("getContractCaseByDynamic", contractCase);
	}	
	
	public ProcessGroup getProcessGroupById(Integer groupId) {
		if(groupId == null)
			return null;
		return (ProcessGroup)getSqlMapClientTemplate().queryForObject("getProcessGroupById", groupId);
	}
	
	public Integer getPageAllProcessCount(Integer indexFlag, Integer groupId)
	{
		Process process = new Process();
		process.setIndexFlag(indexFlag);
		process.setGroupId(groupId);
		return (Integer)getSqlMapClientTemplate().queryForObject("getPageProcessCountByIndexFlag", process);
	}
	
	public List<Process> getPageAllProcess(Integer indexFlag, Integer groupId)
	{
		Process process = new Process();
		process.setIndexFlag(indexFlag);
		process.setGroupId(groupId);
		return (List<Process>)getSqlMapClientTemplate().queryForList("getPageProcessByIndexFlag", process);
	}
	public Long selectCaseSeq()throws Exception{
		Long seq = (Long)getSqlMapClientTemplate().queryForObject("getCaseSeqNumber");
		    if(seq==null){
		    		getSqlMapClient().insert("insertCaseSeqNumber",0L);
		        return 0L;
		    }
		    getSqlMapClient().insert("insertCaseSeqNumber",seq+1);	
			return seq+1;
	}
	
	public List<Entry<ContractCase,List<SubContractCase>>> constructContractCaseAndSubCase(List<ContractCase> caseList,List<SubContractCase>subCaseList){
	    	List<Entry<ContractCase,List<SubContractCase>>> entryList = new ArrayList<Entry<ContractCase,List<SubContractCase>>>();
	    	for(ContractCase case1: caseList){
	    		Entry<ContractCase,List<SubContractCase>> entry = new Entry<ContractCase,List<SubContractCase>>(case1,new ArrayList<SubContractCase>());
	    		for(SubContractCase scc:subCaseList){
	    			if(scc.getMark()==null||case1.getMark()==null){
	    				if(case1.getId().toString().equals(scc.getCaseId()))
	    					entry.getValue().add(scc);
	    			}else{
	    				//remove "sub_"
		    			String subMark = scc.getMark().substring(4,scc.getMark().length());
		    			if(case1.getMark().equals(subMark)){
		    				entry.getValue().add(scc);
		    			}
	    			}
	    			
	    		}
	    		entryList.add(entry);
	    	}
	    	return entryList;
	}
	  
	public void saveContractCase(List<ContractCase>oldCaseList , Long contractId){
		//contractCase 列表 每个contractCase可能有多个SubContractCase..
		
		List<ContractCase> caseList = new ArrayList<ContractCase>();
		List<SubContractCase> subCaseList = new ArrayList<SubContractCase>();
		
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
  		for(ContractCase oldCase:oldCaseList){
  			if(oldCase.getMark().startsWith("sub_")){
  				SubContractCase scc = new SubContractCase();
  				scc.setApplicationCode(oldCase.getApplicationCode());
  				try {
  					scc.setApplicationDate(sdf.parse(oldCase.getApplicationDate()));
				} catch (Exception e) {
					scc.setApplicationDate(new Date());
				}
  				scc.setCaseCode(oldCase.getCaseCode());
  				scc.setDescription(oldCase.getDescription());
  				scc.setCostValue(oldCase.getCostValue());
  			    scc.setOperationCost(oldCase.getOperationCost());
  				scc.setOfficialCost(oldCase.getOfficialCost());
  				scc.setProxyCost(oldCase.getProxyCost());
  				scc.setModifyDate(oldCase.getModifyDate());
  				scc.setSuffixCaseName(oldCase.getSuffixCaseName());
  				scc.setMark(oldCase.getMark());
  				scc.setId(oldCase.getId());
  				scc.setAttachId(oldCase.getAttachId());
  				subCaseList.add(scc);
  			}else {
  				oldCase.setContractId(contractId.toString());
  				caseList.add(oldCase);
  			}
  				
  		}
  		//current list;
  		List<Entry<ContractCase,List<SubContractCase>>> entryList =  constructContractCaseAndSubCase(caseList,subCaseList);
		//previousList
  		List<ContractCase> oldCaseList1 = (List<ContractCase>)getSqlMapClientTemplate().queryForList("getContractCaseByContractCode",contractId.toString());
  		List<SubContractCase> oldSubCaseList = (List<SubContractCase>)getSqlMapClientTemplate().queryForList("getContractSubCaseByContractId",contractId);
  		//construct previous list relation...
  		List<Entry<ContractCase,List<SubContractCase>>> oldEntryList = new ArrayList<Entry<ContractCase,List<SubContractCase>>>();
  		if(oldCaseList1!=null&&!oldCaseList1.isEmpty()){
  			if(oldSubCaseList!=null&&!oldSubCaseList.isEmpty())
  				oldEntryList=constructContractCaseAndSubCase(oldCaseList1, oldSubCaseList);
  			else{
  				for(ContractCase case1:oldCaseList1){
  					oldEntryList.add(new Entry(case1,new ArrayList<SubContractCase>()));
  				}
  			}
  		}
  		
  		//新增合同--ContractCase都为新增.
  		if(oldEntryList.isEmpty()){
  	  		for(Entry<ContractCase,List<SubContractCase>> entry :entryList){
  				Long contractCaseId = ((Integer)getSqlMapClientTemplate().insert("insertContractCase",entry.getKey())).longValue();
  				for(SubContractCase subCase:entry.getValue()){
  					subCase.setCaseId(contractCaseId.toString());
  					subCase.setTypeId("ZZZ");
  					getSqlMapClientTemplate().insert("insertContractSubCase",subCase);
  				}
  			}
  		}else
  			compareAndSave(entryList,oldEntryList);
	}
	/**
	 * 
	 * @param newList 当前提交的
	 * @param oldList 数据库己保存的
	 */
	public void compareAndSave(List<Entry<ContractCase,List<SubContractCase>>>newList,List<Entry<ContractCase,List<SubContractCase>>>oldList){
		List<Entry<ContractCase,List<SubContractCase>>>addList = new ArrayList<Entry<ContractCase,List<SubContractCase>>>();
		List<Entry<ContractCase,List<SubContractCase>>>delList = new ArrayList<Entry<ContractCase,List<SubContractCase>>>();
		List<Entry<ContractCase,List<SubContractCase>>>uppList = new ArrayList<Entry<ContractCase,List<SubContractCase>>>();
		//判断新增的ContractCase
		for(Entry<ContractCase,List<SubContractCase>> entry:newList){
			if(entry.getKey().getId()==null)
				addList.add(entry);
		}
		//判断删除的ContractCase
		for(Entry<ContractCase,List<SubContractCase>> entry:newList){
			boolean isMatched=false;
			if(entry.getKey().getId()==null) continue;//新增的ContractCase不判断.
			for(Entry<ContractCase,List<SubContractCase>> oldEntry:oldList){
				if(entry.getKey().getId().equals(oldEntry.getKey().getId())){
					
					if(entry.getKey().getProcessId().intValue()!=oldEntry.getKey().getProcessId().intValue())
						entry.getKey().setModifyDate(new Date());
					uppList.add(entry);
					isMatched=true;
					break;
				}
			}
			if(isMatched==false)
				delList.add(entry);
		}
		
		//新增的ContractCase
		for(Entry<ContractCase,List<SubContractCase>> entry :addList){
				Long contractCaseId = ((Integer)getSqlMapClientTemplate().insert("insertContractCase",entry.getKey())).longValue();
				if(entry.getKey().getAttachId()!=null)
					updateAttachCaseId(entry.getKey().getAttachId(), contractCaseId, 0L);
				for(SubContractCase subCase:entry.getValue()){
					subCase.setCaseId(contractCaseId.toString());
					subCase.setTypeId("ZZZ");
					insertSubCase(subCase);
				}	
		}
		//删除的ContractCase
		for(Entry<ContractCase,List<SubContractCase>> entry :delList){
			delContractCase(Long.valueOf(entry.getKey().getId()));
		}
		//需要更新的ContractCase
		for(Entry<ContractCase,List<SubContractCase>> entry :uppList){
			getSqlMapClientTemplate().update("updateContractCaseByDynamic",entry.getKey());//update contractCase
			if(entry.getKey().getAttachId()!=null)
				updateAttachCaseId(entry.getKey().getAttachId(), Long.valueOf(entry.getKey().getId()), 0L);
			Entry<ContractCase,List<SubContractCase>> oldEntry = getOldEntry(entry.getKey().getId(), oldList);
			for(SubContractCase subCase:entry.getValue()){
					if(subCase.getId()==null){//新增的SubCase;
						subCase.setCaseId(entry.getKey().getId().toString());
						subCase.setTypeId("ZZZ");
						insertSubCase(subCase);
					}else{//只判断更新
						for(SubContractCase oldScc:oldEntry.getValue()){
							if(oldScc.getId().equals(subCase.getId())){
								uppdateSubCase(subCase);
							    break;
							}
						}
					}
			}
			//判断删除的SubCase
			for(SubContractCase delCase:oldEntry.getValue()){
				boolean isMatched=false;
				for(SubContractCase subCase:entry.getValue()){
					if(subCase.getId()==null)continue;
				    if(subCase.getId().equals(delCase.getId())){
				    	isMatched=true;
				    	break;
				    }
				}
				if(isMatched==false){//没配上，代表当前记录是删除的
					delSubContractCase(delCase.getId().longValue());
				}
			}
		}
	}

	public Entry<ContractCase,List<SubContractCase>> getOldEntry(Integer parentCaseId,List<Entry<ContractCase,List<SubContractCase>>>oldList){
		for(Entry<ContractCase,List<SubContractCase>> entry:oldList){
			if(entry.getKey().getId().equals(parentCaseId))
				return entry;
		}
		return null;
	}
	public void insertSubCase(SubContractCase subCase){
		Long subCaseId = ((Integer)getSqlMapClientTemplate().insert("insertContractSubCase",subCase)).longValue();
		if(subCase.getAttachId()!=null)
			updateAttachCaseId(subCase.getAttachId(), subCaseId, 1L);
	}
	public void uppdateSubCase(SubContractCase subCase){
		getSqlMapClientTemplate().update("updateContractSubCaseByDynamic",subCase);
		if(subCase.getAttachId()!=null)
			updateAttachCaseId(subCase.getAttachId(), subCase.getId().longValue(), 1L);
	}
	public void updateAttachCaseId(Long attachId,Long caseId, Long isSub){
			Map uppmap = new HashMap();
			uppmap.put("id", attachId);
			uppmap.put("caseId", caseId);
			uppmap.put("isSub",isSub);
			getSqlMapClientTemplate().update("updateCaseIdForAttach",uppmap);
	}
    public void delContractCase(Long caseId) {
    	    getSqlMapClientTemplate().delete("deleteCaseAttachForSubCase",caseId);//删除子CASE的附件
    	    Map delMap = new HashMap();
    	    delMap.put("isSub", 0L);
    	    delMap.put("caseId", caseId);
    	    getSqlMapClientTemplate().delete("deleteCaseAttach",delMap);//删除主CASE的附件
			//delete subcase
			getSqlMapClientTemplate().delete("deleteContractSubCase",caseId);//删除子CASE
			//delete case
			getSqlMapClientTemplate().delete("deleteContractCase",caseId);//删除主CASE
	}
    public void delSubContractCase(Long subCaseId){
    	Map delMap = new HashMap();
	    delMap.put("isSub", 1L);
	    delMap.put("caseId", subCaseId);
    	getSqlMapClientTemplate().delete("deleteCaseAttach",delMap);//删除子CASE的附件
    	getSqlMapClientTemplate().delete("deleteContractSubCaseBySubCaseId",subCaseId);//删除子CASE
    }
	public Long saveAttachCase(CaseAttach ca) {
			Long id = ((Integer)getSqlMapClientTemplate().insert("insertCaseAttach",ca)).longValue();
			return id;
	}
	public void delAttachCase(Map map){
			getSqlMapClientTemplate().delete("deleteCaseAttach",map);
	}

	public Long getContractCaseByUser_id_Dept_Count(Map map){
		return (Long) getSqlMapClientTemplate().queryForObject("getContractCaseByUser_id_Dept_Count",map);
	}

	public List<Map> getContractCaseByUser_id_Dept(Map map,Page page){
		if(map.get("caseId")!=null){
			map.put("pageStartRow", 0L);
			map.put("pageEndRow", 1L);
		}else{
			map.put("pageStartRow", page.getPageStartRow());
			map.put("pageEndRow", page.getPageEndRow());
		}
		return (List<Map>)getSqlMapClientTemplate().queryForList("getContractCaseByUser_id_Dept",map);
	}
	@Override
	public List<CaseAttach>getCaseAttach(Long caseId ,boolean isSub){
		Map paraMap = new HashMap();
		paraMap.put("caseId", caseId);
		if(isSub)
		   paraMap.put("isSub", 1);
		else
		   paraMap.put("isSub", 0);
		return (List<CaseAttach>)getSqlMapClientTemplate().queryForList("getCaseAttachByCaseId1",paraMap);
	}

	public List<ContractCase> getContractCaseListByIds(String[] caseIds)
	{
		Map map = new HashMap();
		map.put("caseIds", caseIds);
		
		return (List<ContractCase>)getSqlMapClientTemplate().queryForList("getContractCaseListByIds", map);
	}
	
	public Integer insertCost(CostManage costManage)
	{
		return (Integer)getSqlMapClientTemplate().insert("insertCostManage", costManage);
	}
	
	public List<CostManage> getCostManageListByDynamica(CostManage cost)
	{	
		List<CostManage> results = (List<CostManage>)getSqlMapClientTemplate().queryForList("getCostManageByDynamic", cost);
		
		return results;
	}
	
	public Integer updateContractCase(ContractCase contractCase)
	{
		return (Integer)getSqlMapClientTemplate().update("updateContractCaseByDynamic", contractCase);
	}
	
	public CostManage getCostManageById(Integer id)
	{	
		CostManage result = (CostManage)getSqlMapClientTemplate().queryForObject("getCostManageById", id);
		
		return result;
	}		
	
	public Integer updateCostManage(CostManage costManage)
	{
		return (Integer)getSqlMapClientTemplate().update("updateCostManage", costManage);
	}
}
